package com.tensquare.user.controller;

import com.tensquare.user.pojo.Admin;
import com.tensquare.user.service.AdminService;
import entity.Result;
import entity.StatusCode;
import io.jsonwebtoken.Claims;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import utils.JwtUtils;

import javax.servlet.http.HttpServletRequest;

@RestController
@RequestMapping("admin")
@CrossOrigin
public class AdminController {
    @Autowired
    private AdminService adminService;
    @Autowired
    private JwtUtils jwtUtils;
    @Autowired
    private HttpServletRequest request;
    //1.添加管理员
    @PostMapping
    public Result add(@RequestBody Admin admin){
        adminService.add(admin);
        return new Result(true, StatusCode.OK,"添加管理员成功");
    }
    //2.管理员登录
    @PostMapping("login")
    public Result login(@RequestBody Admin admin){
        Admin loginAdmin= adminService.isTrue(admin);
        if (loginAdmin!=null){
            String token = jwtUtils.getToken(admin.getId(), admin.getLoginname(), "admin");
            return new Result(true,StatusCode.OK,"管理员登录成功!",token);
        }
        return new Result(false,StatusCode.LOGINERROR,"用户名密码输入有误");
    }
    //3.删除管理员
    @DeleteMapping("{adminId}")
    public Result delete(@PathVariable String adminId){
        Claims claims = (Claims) request.getAttribute("claims");
        if (claims!=null && "admin".equals(claims.get("roles"))){
             adminService.delete(adminId);
             return new Result(true,StatusCode.OK,"删除管理员成功");
        }
        return new Result(false,StatusCode.ACCESSERROR,"权限不足");
    }
}
